package com.qq.dao.impl;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.qq.bean.Dynamics;
import com.qq.bean.Users;
import com.qq.dao.BaseDao;
import com.qq.dao.DynamicsDao;

public class DynamicsDaoImpl implements DynamicsDao {

	@Override
	public List<Dynamics> selectMyfriendAllDynamics(String myaccount) {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet res = null;
		List<Dynamics> dy = new ArrayList();
		String sql = "SELECT d.* FROM friend f JOIN dynamics d ON f.friend_accounts = d.user_account WHERE f.qq_accounts = ? ORDER BY dy_time DESC";
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			ps.setString(1, myaccount);
			res = ps.executeQuery();
			while(res.next()) {
				Dynamics dys = new Dynamics();
				dys.setDynamicsId(res.getInt("dynamics_id"));
				dys.setAccounts(res.getString("user_account"));
				dys.setNickname(res.getString("user_nickname"));
				dys.setUserheadimg(res.getString("user_headimg"));
				dys.setSendText(res.getString("send_text"));
				dys.setDynamicsImage(res.getString("dynamics_image"));
				dys.setState(res.getInt("state"));
				dys.setDyTime(res.getDate("dy_time"));
				dy.add(dys);
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(con, ps, res);
		}

		System.out.println(sql);
		return dy;
	}

	@Override
	public int insertmydy(Dynamics dynamics) {
		Connection con = null;
		PreparedStatement ps = null;
		int result = 0;
		String sql = "";
		if(dynamics.getDynamicsImage() == null) {
			sql = "INSERT INTO dynamics(user_account,user_nickname,user_headimg,send_text,state,dy_time) VALUES (?,?,?,?,1,NOW())";;
		}else {
			sql = "INSERT INTO dynamics(user_account,user_nickname,user_headimg,send_text,dynamics_image,state,dy_time) VALUES (?,?,?,?,?,1,NOW())";
		}
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			ps.setString(1, dynamics.getAccounts());
			ps.setString(2, dynamics.getNickname());
			ps.setString(3, dynamics.getUserheadimg());
			ps.setString(4, dynamics.getSendText());
			if(dynamics.getDynamicsImage() !=null) {
				ps.setString(5, dynamics.getDynamicsImage());
			}
			result = ps.executeUpdate();
		} catch (SQLException e) {
			
			e.printStackTrace();
		} finally {
			BaseDao.closeAll(con, ps, null);
		}
		return result;
	}

}
